//
//  TabBarViewController.m
//  sklive
//
//  Created by Macx on 2017/4/25.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "TabBarViewController.h"
#import "HomeViewController.h"
#import "MallHomeViewController.h"
#import "PerCenterViewController.h"
#import "MiddleTabBar.h"
#import "PostsTextViewController.h"
#import "AddResumeViewController.h"
// Nav基类
#import "BaseNavViewController.h"

#import "LCButton.h"
#import "TCVideoRecordViewController.h"
#import "OpenLiveViewController.h"
#import "PostQuestionViewController.h"
#import "QAViewController.h"
#import "AddJobViewController.h"
#import "WebViewWithStringVC.h"
#import "WKWebViewController.h"
#import <AXWebViewController.h>
#import "JPUSHService.h"

@interface TabBarViewController () <MiddleTabBarDelegate, UITabBarControllerDelegate>

@property (strong, nonatomic) WKWebViewController *wkWebView;

@end

@implementation TabBarViewController {
    UIView *_bigBgView;
    UIView *_bgView;
    UIButton *_closeBtn;
}

// 自定义了TabBarController 之后必须实现以下 ！！！
-(void)viewWillAppear:(BOOL)animated {
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    [self.selectedViewController beginAppearanceTransition: YES animated: animated];
    
}

-(void) viewDidAppear:(BOOL)animated
{
    [self.selectedViewController endAppearanceTransition];
}

-(void) viewWillDisappear:(BOOL)animated
{
    [self.selectedViewController beginAppearanceTransition: NO animated: animated];
}

-(void) viewDidDisappear:(BOOL)animated
{
    [self.selectedViewController endAppearanceTransition];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(comRecord:)name:@"completeRecord" object:nil];
	
	/**前台运行时，可接收由JPush下发的自定义消息
	 
	      *获取自定义消息（只有在前端运行的时候才能收到自定义消息的推送）
	 
	      *  kJPFNetworkDidReceiveMessageNotification// 收到消息(非APNS)
	 
	      */
	
	NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
	
	[defaultCenter addObserver:self
					  selector:@selector(networkDidReceiveMessage:)
						  name:kJPFNetworkDidReceiveMessageNotification
						object:nil];

    
    // 光状态栏,用于使用在黑暗的背景。在iOS 7.0及以后。
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    BaseNavViewController *homeNav = [self buildNavViewControllerWithClassName:@"HomeViewController" title:@"首页" image:@"tab_index_grey" selectedImage:@"tab_index_color"];
	BaseNavViewController *shopNav = [self buildNavViewControllerWithClassName:@"MallHomeViewController" title:@"商场" image:@"tab_shop_grey" selectedImage:@"tab_shop_color"];
	BaseNavViewController *jobNav = [self buildNavViewControllerWithClassName:@"JobHomeViewController" title:@"招聘" image:@"tab_job_grey" selectedImage:@"tab_job_color"];
    BaseNavViewController *perNav = [self buildNavViewControllerWithClassName:@"PerCenterViewController" title:@"个人中心" image:@"tab_my_grey" selectedImage:@"tab_my_color"];
    
    // 设置导航背景风格颜色
//    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithHexString:UIMainColor alpha:1]];
    // 设置导航按钮风格颜色
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    // 隐藏导航返回按钮的文字
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
    // 设置tabbar不透明
    [UITabBar appearance].translucent = YES;
    
    
    self.viewControllers = @[homeNav, shopNav, jobNav, perNav];
    
    // 中间tabbar
    MiddleTabBar *tabBar = [[MiddleTabBar alloc] init];
    tabBar.MyDelegate = self;
    tabBar.itemNum = (int)self.viewControllers.count;
    [self setValue:tabBar forKey:@"tabBar"];
    
    // 中间响应
    
    _bigBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
//    [self.view addSubview:_bigBgView];
    _bigBgView.backgroundColor  = [kBlackColor colorWithAlphaComponent:0.5];
//    _bigBgView.hidden = YES;
    [_bigBgView addTarget:self action:@selector(hiddenView)];
    
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, SH(4)*3, SCREEN_WIDTH, SH(4))];
    [_bigBgView addSubview:_bgView];
    _bgView.backgroundColor = [kWhiteColor colorWithAlphaComponent:0.8];
    
    NSArray *imgArr;
    NSArray *textArr;
    
	int state = [LZCTools thinkEnv];
    if (GetUserDefaule(USERINFO)[@"role"] && ![GetUserDefaule(USERINFO)[@"role"] isEqualToString:@"1"]) {
		imgArr = @[@"tab_reease_alive", @"tab_reease_goods", @"tab_reease_job", @"tab_reease_resume"];
		textArr = @[@"发起直播", @"发布商品", @"发布岗位", @"创建简历"];
    }
    else {
		
    }
    
    CGFloat btnW = (SCREEN_WIDTH-70)/4;
	NSString *role = GetUserDefaule(USERINFO)[@"role"];
    for (int j = 0; j < imgArr.count; j++) {
        LCButton *indexBtn = [[LCButton alloc] initWithFrame:CGRectMake(20+(btnW+10)*j, 20, btnW, btnW)];
        [indexBtn setTitle:textArr[j] forState:UIControlStateNormal];
        [indexBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        [indexBtn setImage:IMAGE(imgArr[j]) forState:UIControlStateNormal];
        indexBtn.tag = 1+j;
        
        
        //这里按钮排版相对复杂，解释一下，我的思路就是这四个按钮默认位置就是定好的一排,20+(btnW+10)*j,当某些按钮因为角色不同，后面的按钮就相应往前挪多少位，就是j-x，比如个人角色只需要最后一个按钮，前面的都不需要，那就是j-3，这样一来就比较具体了，清晰很多。
		switch ([role integerValue]) {
			case 2:
				if (state) {
					if (indexBtn.tag == 1) {
						indexBtn.frame = CGRectMake(20+(btnW+10)*(j), 20, btnW, btnW);
						[_bgView addSubview:indexBtn];
					}
					if (indexBtn.tag == 4) {
						indexBtn.frame = CGRectMake(20+(btnW+10)*(j-2), 20, btnW, btnW);
						[_bgView addSubview:indexBtn];
					}
				}
				else {
					if (indexBtn.tag == 4) {
						indexBtn.frame = CGRectMake(20+(btnW+10)*(j-3), 20, btnW, btnW);
						[_bgView addSubview:indexBtn];
					}
				}
				
				break;
			case 3:
				if (indexBtn.tag == 1 || indexBtn.tag == 2) {
					indexBtn.frame = CGRectMake(20+(btnW+10)*j, 20, btnW, btnW);
					[_bgView addSubview:indexBtn];
				}
				
				break;
			case 4:
				if (indexBtn.tag != 3) {
					if (j != 3) {
						indexBtn.frame = CGRectMake(20+(btnW+10)*j, 20, btnW, btnW);
					}
					else
						indexBtn.frame = CGRectMake(20+(btnW+10)*(j-1), 20, btnW, btnW);
					[_bgView addSubview:indexBtn];
				}
				
				break;
			case 5:
				if (indexBtn.tag == 3) {
					indexBtn.frame = CGRectMake(20+(btnW+10)*(j-2), 20, btnW, btnW);
					[_bgView addSubview:indexBtn];
				}
				break;
			case 6:
				if (indexBtn.tag != 4) {
					indexBtn.frame = CGRectMake(20+(btnW+10)*j, 20, btnW, btnW);
					[_bgView addSubview:indexBtn];
				}
				
				break;
			default:
				break;
		}
        [indexBtn addTarget:self action:@selector(postClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_bgView addSubview:_closeBtn];
//    CGFloat btnH = _bgView.height - (SW(2)+SW(40)+10);
    CGFloat btnH = _bgView.height - (20+btnW);
    _closeBtn.center = CGPointMake(_bgView.centerX, _bgView.height-btnH/2);
    _closeBtn.bounds = CGRectMake(0, 0, btnH, btnH);
    [_closeBtn setImage:IMAGE(@"icon_fb_close") forState:UIControlStateNormal];
    [_closeBtn addTarget:self action:@selector(closeMidViewClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.delegate = self;
    
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    
    static NSString *tabBarDidSelectedNotification = @"tabBarDidSelectedNotification";
    //当tabBar被点击时发出一个通知
    [[NSNotificationCenter defaultCenter] postNotificationName:tabBarDidSelectedNotification object:nil userInfo:nil];
}

/**
 *  快速创建导航视图控制器的方法
 *
 *  @param className         视图控制器的类名
 *  @param title             显示在视图控制器的导航标题
 *  @param imageName         视图控制器的标签选项的普通状态图片
 *  @param selectedImageName 视图控制器的标签选项的选中状态图片
 *
 *  @return 导航控制器对象
 */
-(BaseNavViewController *)buildNavViewControllerWithClassName:(NSString *)className title: (NSString *)title image:(NSString*)imageName selectedImage: (NSString *)selectedImageName {
    
    Class vcClass = NSClassFromString(className);
    UIViewController *newVc = nil;
    if (vcClass) {
        newVc = (UIViewController *)[[vcClass alloc]init];
    }
    
    BaseNavViewController *nav = [[BaseNavViewController alloc]initWithRootViewController:newVc];
	
	
    [nav.navigationBar setTranslucent:NO];
    // 设置导航栏背景颜色
    nav.navigationBar.barTintColor = [UIColor colorWithHexString:UIMainColor alpha:1.0];
    // 设置导航栏字体颜色
    [nav.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    
    newVc.title = title;
    // 设置图片并不受系统的tintcolor所渲染
    newVc.tabBarItem.image = [[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    newVc.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    // 设置字体颜色
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithHexString:UITabBarNormalColor alpha:1.0], NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:                                                         [NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithHexString:UITabBarSelectedColor alpha:1.0],NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];
    
    newVc.tabBarController.selectedViewController = self.tabBarController.childViewControllers[0];
    
    return nav;
    
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return self.childViewControllers.count > 1;
}


#pragma ===== 响应方法 =====
/**
 发起问诊被点击
 */
- (void)tabBarPlusBtnClick:(MiddleTabBar *)tabBar {
    
    NSLog(@"middleTabBar被点击");
	NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
    if (role != 0 && role != 1) {
//        _bigBgView.hidden = NO;
        [self.view addSubview:_bigBgView];
    }
    else {
        UIAlertController *alert = [LZCTools alertMessage:@"您尚未进行实名认证，无法进行此操作"];
        [self presentViewController:alert animated:YES completion:nil];
    }
}
// 隐藏视图
- (void)closeMidViewClick:(UIButton *)sender {
    [self hiddenView];
}
// 隐藏视图
- (void)hiddenView {
//    _bigBgView.hidden = YES;
    [_bigBgView removeFromSuperview];
}

- (void)postClick:(LCButton *)sender {
    switch (sender.tag) {
        case 4:
        {
			AddResumeViewController *vc = [[AddResumeViewController alloc] init];
			
			[self presentViewController:vc animated:YES completion:nil];
			[self hiddenView];
        }
            break;
        case 2:
        {
			NSString *urlStr;
            urlStr = [NSString stringWithFormat:@"%@/mobile/goods/create/token/%@",APIBackEndUrl, [GetUserDefaule(Token) valueForKey:@"access_token"]];
			//urlStr = @"http://www.baidu.com";
			
			//[self.wkWebView loadWebURLSring:urlStr];
			//[self.selectedViewController pushViewController:self.wkWebView animated:YES];
			
			AXWebViewController *webViewVC = [[AXWebViewController alloc] initWithAddress:urlStr];
			webViewVC.showsToolBar = NO;
			webViewVC.navigationController.navigationBar.translucent = NO;
			webViewVC.navigationType = AXWebViewControllerNavigationBarItem;
			[self.selectedViewController pushViewController:webViewVC animated:YES];
			
			[self hiddenView];
        }
            break;
        case 3:
        {
			AddJobViewController *vc = [[AddJobViewController alloc] init];
			[self presentViewController:vc animated:YES completion:nil];
			[self hiddenView];
             
        }
            break;
        case 1:
        {
            OpenLiveViewController *openVC = [[OpenLiveViewController alloc] init];
            [self presentViewController:openVC animated:YES completion:nil];
            [self hiddenView];
        }
            break;
        default:
            break;
    }
}


// 主页tableView是否滚动接收到通知
- (void)comRecord:(NSNotification *)notification {
    
    NSLog(@"－－－－－录制完视频返回收到通知------\n = %@", notification.userInfo);
    
    if ([notification.userInfo[@"isRecord"] isEqualToString:@"0"]) {
        PostsTextViewController *postVC = [[PostsTextViewController alloc] init];
        postVC.type = @"2";
//        postVC.goodId = @"";
        postVC.videoPath = notification.userInfo[@"path"];
        postVC.videoCover = notification.userInfo[@"cover"];
        [self presentViewController:postVC animated:YES completion:nil];
    }
    
}
- (WKWebViewController *)wkWebView {
	if (!_wkWebView) {
		_wkWebView = [[WKWebViewController alloc] init];
	}
	return _wkWebView;
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
	
	   /**
		
		     *参数描述：
		
		     content：获取推送的内容
		
		     extras：获取用户自定义参数
		
		     customizeField1：根据自定义key获取自定义的value
		
		     */
	NSDictionary * userInfo = [notification userInfo];
	
	NSString *content = [userInfo valueForKey:@"content"];
	
	NSDictionary *extras = [userInfo valueForKey:@"extras"];
	
	NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; ///服务端传递的Extras附加字段，key是自己定义的
	
	NSInteger badge = [[[userInfo valueForKey:@"aps"] valueForKey:@"badge"] integerValue];
	
	NSLog(@"%jiaobao--ld",(long)badge);
	
	NSLog(@"custuserInfo:%@",userInfo);
	
	NSLog(@"custcontent:%@",content);
	
	NSLog(@"custextras:%@",extras);
	
	NSLog(@"customizeField1:%@",customizeField1);
	
	NSLog(@"cust获取注册ID:%@",[JPUSHService registrationID]);
	
}

//移除广播监听。

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
